<?php
namespace app\admin\controller;
use app\model\PayLog;
use app\model\Users;
use app\model\Order;
use think\Session;

class UserController extends AuthController
{
    protected function _initialize(){
        parent::_initialize();
    }

    public function index(){
        $name = $this->request->param('name');

        if ($name != '') {
            $user = new Users();
            $result = $user
                ->where('nickname','like','%'.$name.'%')
                ->paginate(20);
        }else{
            $user = new Users();
            $result = $user
                ->order('credit desc')
                ->paginate(20);
        }

        $this->assign('list',$result);
        return $this->fetch();
    }

    /**
     * 用户订单
     */
    public function order(){
        $id = $this->request->param('id');
        if ($id == ''){
            $this->error('用户id不正确');
        }

        $order = new Order();
        $result = $order
            ->order('create_time desc')
            ->where('user_id',$id)
            ->paginate(20);

        $this->assign('list',$result);
        return $this->fetch();
    }

    /**
     * 增加积分
     * @return array
     * @throws \think\Exception
     */
    public function addCredit(){
        $id = $this->request->post('id');
        $value = $this->request->post('value');
        $user = Users::get(['id'=>$id]);
        if($user->setInc('credit',$value)){
            $pay = new PayLog;
            $pay->save([
                'user_id' => $id,
                'username' => $user->nickname,
                'type' => 1,
                'credit' => $value,
                'reason' => '管理员:'.Session::get('admin_name').'增加积分',
                'status' => 1,
            ]);
            return msgReturn(true,'用户积分增加成功');
        }else{
            return msgReturn(false,'error');
        }
    }

}